<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>state</title>
  </head>
  <body>
    <div id="test"></div>
    <script
      src="https://unpkg.com/react@16/umd/react.production.min.js"
      crossorigin
    ></script>
    <script
      src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"
      crossorigin
    ></script>

    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

    <script type="text/babel">
      class Weatch extends React.Component {
        constructor(props) {
          super(props);
          //初始化状态
          this.state = {
            isHot: false,
          };
          //解决 h2Click 中this指向问题
          this.h2Click = this.h2Click.bind(this);
        }

        render() {
          return (
            <h2 onClick={this.h2Click}>
              点击发生变化{this.state.isHot ? "变化1" : "变化2"}
            </h2>
          );
        }

        h2Click() {
          //h2Click 放在哪里? --------- Weatch原型对象上,供实例使用
          //由于 h2Click 是作为 onClick的回调,所以不是通过实例调用的,是直接调用
          //类中方法默认开启了局部的严格模式,所以h2Click中的this是undefined,需要在构造器中通过bind改变this
          const isHot = this.state.isHot;
          console.log("点击事件");
          console.log(this);

          //React 状态改变必须通过setState进行更新,且更新是合并,不是替换
          this.setState({ isHot: !isHot });
        }
      }

      ReactDOM.render(<Weatch />, document.getElementById("test"));
    </script>
  </body>
</html>
